from json import dumps
from os import environ
from uuid import uuid1

from xlwt import Workbook


class ExportData():
    def __init__(self):
        super(ExportData, self).__init__()

    def change(self, widget, mode, history):
        """ Show data by selection mode of history. """
        widget.clear()
        widget.addItems(['No Item...'] if not history[mode] else history[mode])

    def export(self, mode, format, history):
        """ Export data in selected format. """
        save = f'{environ["HOME"]}/.cache/anima/history-{uuid1().int}.{format}'

        if len(history[mode]) > 0:
            if format in ('md', 'txt'):
                with open(save, 'w') as f:
                    [f.write(f'{i}\n') for i in history[mode]]
            elif format == 'json':
                with open(save, 'w') as f:
                    f.write(dumps(history[mode], sort_keys=False, indent=4,
                                   ensure_ascii=False, separators=(',', ': ')))
            elif format == 'xlsx':
                writing_book = Workbook()
                writing = writing_book.add_sheet(f'export history {mode}')
                [writing.write(i, 0, v) for i, v in enumerate(history[mode])]
                writing_book.save(save)
